/**
 * Copyright [2019] [LiBo/Alex of copyright liboware@gmail.com ]
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyts.infodb.file.web.file;

import com.hyts.infodb.error.subclass.ControllerException;
import com.hyts.infodb.file.bean.file.FileBO;
import com.hyts.infodb.file.bean.file.FileVO;
import com.hyts.infodb.file.service.file.FileExtService;
import com.hyts.infodb.file.service.file.FileService;
import com.hyts.infodb.utils.FileUtils;
import com.hyts.infodb.utils.ResponseInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

/**
 * @project-name:infodb
 * @package-name:com.hyts.infodb.file.web.file
 * @author:LiBo/Alex
 * @create-date:2020-01-18 17:36
 * @copyright:libo-alex4java
 * @email:liboware@gmail.com
 * @description:
 */
@Slf4j
@RequestMapping("/file/ext")
@RestController
public class FileExtController {


    @Autowired
    FileExtService fileExtService;

    @Autowired
    FileService fileService;


    @PostMapping("uploadFile")
    public FileVO uploadFile(@RequestParam("file") MultipartFile file,
                             @RequestParam("bizNo") Long bizNo,
                             @RequestParam("directoryId") Long directoryId ) {
        try {
            return fileExtService.uploadLocal(file,bizNo,directoryId);
        } catch (ControllerException e) {
            log.error("上传文件失败!",e);
            return new FileVO();
        }
    }


    /**
     * 文件下载
     * @param fileId
     * @param res
     */
    @RequestMapping(value = "/downloadFile/{fileId}")
    public void downloadFile(@PathVariable("fileId") Long fileId, HttpServletResponse res) {
        try {
            FileBO fileBO = new FileBO();
            fileBO.setId(fileId);
            fileExtService.downloadLocal(fileBO, res);
        } catch (ControllerException e) {
            log.error("下载文件失败!",e);
        }
    }

    /**
     * 文件查看
     */
    @RequestMapping(value = "/view", method = RequestMethod.GET)
    public ResponseEntity<InputStreamResource> view(@RequestParam("fileId") Long fileId){
        FileBO file = new FileBO();
        file.setId(fileId);
        InputStream inputStream = fileExtService.lookFile(file);
        FileVO fileVO = fileService.loadFile(file);
        if (inputStream == null) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        HttpHeaders header = new HttpHeaders();
        if (FileUtils.match(fileVO.getContent().getFileName(), "jpg", "png", "gif", "bmp", "tif")) {
            header.setContentType(MediaType.IMAGE_JPEG);
        } else if (FileUtils.match(fileVO.getContent().getFileName(), "html", "htm")) {
            header.setContentType(MediaType.TEXT_HTML);
        } else if (FileUtils.match(fileVO.getContent().getFileName(), "pdf")) {
            header.setContentType(MediaType.APPLICATION_PDF);
        } else {
            header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        }
        header.add("X-Filename", fileVO.getContent().getFileName());
        //header.add("X-MD5", fileInfo.getMd5());
        return new ResponseEntity(new InputStreamResource(inputStream), header, HttpStatus.OK);
    }


    /**
     * 逻辑删除文件
     */
    @RequestMapping(value = "/deleteFile")
    public ResponseInfo<?> deleteFile(@RequestParam("fileId") Long fileId) {
        try {
            FileBO fileBO = new FileBO();
            fileBO.setId(fileId);
            return ResponseInfo.success(fileExtService.removeFileLocal(fileBO));
        }catch (ControllerException e){
            log.error("删除文件",e);
            return ResponseInfo.error(null);
        }
    }

}
